<template>
  <div id="attach" style="width: 100%; justify-content: center; display: flex">
    <div style="width: 100%">
      <div v-if="hteFile.id && hteFile.publishState != 2 && hteFile.disable != 1">
        <hte-upload    dbKey="Trd" ftpKey="ftp"
              busField="library"
              busType="1" 
           v-model="fileList" :onSuccess="successUpload" 
            :show-file-list="false"
          :before-upload="beforUpload(0)"
          ref="upload"
          >
           
        
          <span slot="btn">
             <a-button style="margin-left: 10px; margin-bottom: 10px" icon="setting" @click="settingContentFlag"> 设置正文附件 </a-button>
            <a-button style="margin-left: 10px; margin-bottom: 10px" icon="delete" @click="deleteAttach"> 删除 </a-button>
          </span>
          </hte-upload>
        <!-- <ht-upload
          ref="upload"
          class="upload-demo"
          multiple
          dbKey="Trd"
          busField="library"
          busType="1"
          ftpKey="ftp"
          v-model="fileList"
          :show-file-list="false"
          :before-upload="beforUpload(0)"
          
           :on-success="successUpload"
        >
          <el-button slot="trigger" size="small" type="" icon="el-icon-plus">新增附件</el-button>
         
           <a-button style="margin-left: 10px; margin-bottom: 10px" icon="setting" @click="settingContentFlag"> 设置正文附件 </a-button>
          <a-button style="margin-left: 10px; margin-bottom: 10px" icon="delete" @click="deleteAttach"> 删除 </a-button>
        </ht-upload> -->
      </div>
      <div>
        <a-table
          :columns="columns"
          :data-source="attachList"
          rowKey="id"
          bordered
          :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
          @change="handleTableChange"
          :pagination="ipagination"
        >
          <span slot="fileName" slot-scope="text, record" >
            <a v-if="!!record.attachId" icon="download" @click="handlePreview(record)">{{ text }}</a>
            <span style="color:rgb(205, 205, 205)" v-else>{{ text + '(请点击保存上传文件)' }}</span>
            
          </span>
        
          <span slot="contentFlag" slot-scope="text, record" >

            {{text == 1 ?'是':'否'}}
            
          </span>
          <span slot="action" slot-scope="text, record" v-if="!!record.attachId">
            <a icon="download" @click="handleDownload(record)">下载</a>
          </span>
        </a-table>
      </div>
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import '@/config/upload.install.js'
import '@/config/hteupload.install.js';
import { formatFileSize, endWith } from '@/utils/common.js'
import { getAction,postAction ,postActionAsync,getActionAsync} from '@/api/manage'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import cloneDeep from 'lodash/cloneDeep'
const columns = [
  {
    title: '附件名称',
    dataIndex: 'fileName',
    key: 'fileName',
    scopedSlots: { customRender: 'fileName' },
   width: '40%',
  },
  {
    title: '文件大小',
    customRender:function (text) {
      var size = !text?0:text;
        return formatFileSize(size)
      },
      dataIndex: 'size',
    key: 'size',
     width: '15%',
  },
  {
    title: '上传时间',
    dataIndex: 'uploadTime',
    key: 'uploadTime',
    width: '15%',
  },
  {
    title: '正文附件',
    dataIndex: 'contentFlag',
    key: 'contentFlag',
    width: '10%',
    scopedSlots: { customRender: 'contentFlag' },
  },
  {
    title: '操作',
    dataIndex: 'action',
    //align: 'center',
    //fixed: 'right',
     width: '20%',
    scopedSlots: { customRender: 'action' },
  },
]
export default {
  components: {},
  props: {
    hteFile: {
      type: Object,
      default: () => {},
    },
    parentId: {
      type: String,
      default: null,
    },
  },
  data() {
    return {
      columns,
      fileList: [],
      fileListOne:[],
      attachList: [],
      busKey: '',
      selectedRowKeys: [],
      selectionRows:[],
      url: {
        list: '/lib/attach/list',
        updateFilePath: '/lib/attach/updateFilePath',
        updateBatchFilePath:'/lib/attach/updateBatchFilePath',
        delete: '/lib/attach/deleteAttach',
        editContentFlag: '/lib/attach/editContentFlag',
        updateNoUpload: '/lib/attach/updateNoUpload',
      },
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,

        total: 0,
      },
    }
  },
  created() {
    this.busKey = this.hteFile.id
  },
  methods: {
    /**
     * 表结构切换页码
     */
    handleTableChange(pagination, filters, sorter) {
      this.ipagination = pagination
      this.ipagination.pageNo = this.ipagination.current
      this.listAttachment(this.fileId, this.version)
    },
    beforUpload(attachId) {
      
      if (!this.hteFile.id || this.hteFile.id === 0) {
        return
      }
      this.attachId = attachId
    },
    afterUpload(response,file,fileList) {
      debugger
      // this.attachList.push(response[0])
      getAction(this.url.updateFilePath, {
        fileId: this.hteFile.id,
        attachId: response[0].id,
        libAttachId: this.attachId,
      }).then((res) => {
        if (res.success) {
          if (res.result.draftVersion == this.hteFile.draftVersion) {
            this.listAttachment(this.hteFile.id, this.hteFile.draftVersion)
          } else {
            this.$emit('reload', res.result)
          }
        } else {
          this.$message.error(res.message)
        }
      })
    },
    async listAttachment(fileId, version) {
      if (fileId > 0) {
        this.fileId = fileId
        this.version = version
        this.ipagination.id = fileId
        this.ipagination.version = version
        let that = this
        let param = Object.assign({}, this.ipagination)
        delete param.pageSizeOptions
        delete param.showTotal
        let res = await getActionAsync(this.url.list, param)
        if (res.success) {
            this.attachList = res.result.records || res.result
            if (res.result.total) {
              that.ipagination.total = res.result.total
            } else {
              that.ipagination.total = 0
            }
             that.$emit("getTotal",that.ipagination.total)
          }
      }
    },
    onSelectChange(selectedRowKeys,selectionRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows;
    },
    deleteAttach() {
        const that = this
      if (this.selectedRowKeys.length === 0) {
        this.$message.error('请选中要删除的附件')
        return false
      }
      
      this.$confirm({
        title: '确认删除',
        content: '是否删除选中附件?',
        onOk: function () {
          let ids = ''
          that.selectedRowKeys.forEach((key) => {
            ids += key + ','
          })
          getAction(that.url.delete, { fileId: that.hteFile.id, ids: ids }).then((res) => {
            if (res.success) {
              that.$message.success('删除成功')
              that.fileList = []
              that.selectedRowKeys = []
              that.selectionRows = []
              if (res.result.draftVersion == that.hteFile.draftVersion) {
                that.listAttachment(that.hteFile.id, that.hteFile.draftVersion)
              } else {
                that.$emit('reload', res.result)
              }
            } else {
              that.$message.error('删除失败')
            }
          })
        },
      })
    },
    settingContentFlag(){
      if (this.selectedRowKeys.length != 1) {
        this.$message.error('请选择单个附件')
        return false
      }
      const that = this
      this.$confirm({
        title: '确认设置显示正文附件',
        content: '设置显示正文附件',
        onOk: function () {
          let ids = ''
          that.selectedRowKeys.forEach((key) => {
            ids += key
          })
          getAction(that.url.editContentFlag, { fileId: that.hteFile.id, id: ids }).then((res) => {
            if (res.success) {
              that.$message.success('设置成功')
             
              if (res.result.draftVersion == that.hteFile.draftVersion) {
                that.listAttachment(that.hteFile.id, that.hteFile.draftVersion)
              } else {
                that.$emit('reload', res.result)
              }
            } else {
              that.$message.error('设置失败')
            }
          })
        },
      })
    },
    handleDownload(row) {
       let that = this
      let record = cloneDeep(row) 
      record.id = record.attachId
      that.$refs.upload.download(0,[record])
     
    },
    handlePreview(row) {
     
       let that = this
      let record = cloneDeep(row) 
      record.id = record.attachId
      that.$refs.upload.handlePreview(record)
      
    },
    updateNoUpload(libAttachId) {
      getAction(this.url.updateNoUpload, { libAttachId: libAttachId }).then((res) => {
        if (res.success) {
          this.$message.success('更新成功')
          this.listAttachment(this.hteFile.id, this.hteFile.draftVersion)
        } else {
          this.$message.error('更新失败')
        }
      })
    },
     
    async uploadBatch(fileList){
      debugger
      let newFile =  fileList.filter(item=>{
          return !this.attachList.find(attach=>{
            return attach.attachId == item.id
          })
       })
       let that = this
       
        let data = {}
        data.fileId = this.hteFile.id;
        data.attachmentList = newFile
        console.log(JSON.stringify(newFile))
      let res = await postActionAsync(that.url.updateBatchFilePath, data)
      
      
      if (res.success) {
        if (res.result.draftVersion == that.hteFile.draftVersion) {
          that.listAttachment(that.hteFile.id, that.hteFile.draftVersion)
        } else {
          that.$emit('reload', res.result)
        }
      } else {
        that.$message.error(res.message)
      }
     
      
     },  
      successUpload(response,file,fileList){
        
          this.uploadBatch([file])
      },

  },
  watch: {
    'hteFile.id': {
      handler: function (newVal, oldVal) {
        if (newVal != oldVal) {
          this.listAttachment(newVal, this.hteFile.draftVersion)
        }
      },
    },
    'hteFile.draftVersion': {
      handler: function (newVal, oldVal) {
        if (newVal != oldVal) {
          this.listAttachment(this.hteFile.id, newVal)
        }
      },
    },
      fileList:{
        handler: function (newVal, oldVal) {
          
          // this.uploadBatch(newVal)
         
        },
        deep:true
    },
  }
}
</script>

<style>
</style>